
#include "stdafx.h"
#include "CombatState_Charging.h"
#include "Combat/EvtCombat.h"
#include "Event/EvtImp.h"
#include "Combat/CombatSysImp.h"
#include "Entity/EntityIf.h"
#include "Combat/CombatDefinition.h"
#include "Move/EvtMove.h"


enum
{
	time_InCharging		=	15000,
};

CombatState_Charging::CombatState_Charging(void)

{
}

CombatState_Charging::~CombatState_Charging()
{
}

void
CombatState_Charging::enter()
{
	//
	//	if m_nTTL == 0, ICombatSys will keep in Charging states until some one else set me to another state
	//	if m_nTTL > 0,  ICombatSys will transfer to casting state when time expired
	//

	m_nTTL = 0;
}

void
CombatState_Charging::leave()
{
	//
	//	In range
	m_wpEntity->setMoveState(Move::mst_Idle);
}


bool 
CombatState_Charging::update(int nElapse)
{
	m_nTTL-= nElapse;

	if (m_nTTL<=0)
	{
		IEntity* pTarget = m_wpCombat->getTargetCC();
		if (pTarget)
		{

			int  nDstTileX = 0;
			int  nDstTileZ = 0;
			//pTarget->getTilePosition(nDstTileX, nDstTileZ);

			int  nCurTileX = 0;
			int  nCurTileZ = 0;
			//m_wpEntity->getTilePosition(nCurTileX, nCurTileZ);

			nCurTileX -= nDstTileX;
			nCurTileZ -= nDstTileZ;
			if ((nCurTileX*nCurTileX + nCurTileZ*nCurTileZ)<16)
			{
				m_wpCombat->setState(Combat::CBS_Casting);
			}
			else
			{
				//
				//	If target is moving or I am not moving
				//
				if ( pTarget->getMoveState()==Move::mst_Moving ||
					m_wpEntity->getMoveState()!=Move::mst_Moving)
				{
					EvtImp ge(EVT_Move, int (nDstTileX * 1000),  int (nDstTileZ * 1000), Move::MT_RUN);
					m_wpEntity->onEvent(ge);
				}

				m_nTTL = 1000;
			}
		}
		else
		{
			m_wpCombat->setState(Combat::CBS_Ready);
		}
	}
	return true;
}



void 
CombatState_Charging::onEvent(IEvt& evt)
{
	if (evt.getID()==EVT_CastStart)
	{
		if (!m_wpCombat->isCalculator())
		{
			GECast* pGE = static_cast<GECast*>(&evt);
			m_wpCombat->onEvent_Cast(evt);
			m_wpCombat->setState(Combat::CBS_Ready);
		}
		else
		{
			LOG_ERROR("Failed, calculator should not received cast start when charging!\n");
		}
	}
	else if (evt.getID()==EVT_CastEnd)
	{
		if (!m_wpCombat->isCalculator())
		{
			m_wpCombat->setState(Combat::CBS_CoolDown);
		}
		else
		{
			LOG_ERROR_V("Failed to cast end in : %d !\n", m_wpCombat->getStateName());
		}
	}
	else if (evt.getID()==EVT_CastResult)
	{
		m_wpCombat->onEvent_CastResult(evt);
	}
	else if (evt.getID()==EVT_CastPrep)
	{
		m_wpCombat->onEvent_CastPrep(evt);
	}
	else if (evt.getID()==EVT_TargetSelected)
	{
		m_wpCombat->onEvent_Target(evt);
	}
}


